import { Sort } from "../public/Sort"
import { DefaultCompare, ICompareFunction, CompareEnum } from "../public/Utils"

/**
 * 冒泡排序
 * 比较相邻的两个项，如果第一个比第二个大，则交换它们。
 * **/
 export class BubbleSort<T> extends Sort<T> {
    constructor(array: Array<T> = [], compareFun: ICompareFunction = new DefaultCompare()) {
        super(array, compareFun)
    }
    sort(): void {
        //获取数组长度
        const { length } = this.array
        for (let i: number = 0; i < length; i++) {
            //从数组的0号元素遍历到数组的倒数第2号元素
            for (let j: number = 0; j < length - 1; j++) {
                //如果j > i,则交换两个元素的位置
                if (this.compare.compare(this.array[i], this.array[j]) === CompareEnum.BIGGER) {
                    this.swap(this.array, j, i)
                }
            }
        }
    }
}

const BubbleSortTest = (): void => {
    const array = [12, 44, 67, 15, 54]
    const bubbleSort: Sort<Number> = new BubbleSort<Number>(array)
    bubbleSort.sort()
    console.log(array);
}
BubbleSortTest()
